/**
 *  Document   : AuthenticationTreatment
 *  Created on : 26 juil. 2008, 18:20:08
 *  Author     : Rivo
 */
package gla.centralhotel.uiweb.treatment;

import com.sun.rave.web.ui.appbase.AbstractRequestBean;
import gla.centralhotel.business.IAuthentication;
import gla.centralhotel.exception.IllegalAuthenticationException;
import gla.centralhotel.exception.InputDataException;
import gla.centralhotel.model.Agency;
import gla.centralhotel.model.Manager;
import javax.ejb.EJB;
import javax.faces.FacesException;
import gla.centralhotel.uiweb.ApplicationBean;
import gla.centralhotel.uiweb.Login;
import gla.centralhotel.uiweb.SessionBean;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;

/**
 * <p>Request scope data bean for your application.  Create properties
 *  here to represent data that should be made available across different
 *  pages in the same HTTP request, so that the page bean classes do not
 *  have to be directly linked to each other.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 *
 */
public class AuthenticationTreatment extends AbstractRequestBean {

    @EJB
    private IAuthentication authentication;
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>

    /**
     * <p>Construct a new request data bean instance.</p>
     */
    public AuthenticationTreatment() {
    }

    /**
     * <p>This method is called when this bean is initially added to
     * request scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * request scope.</p>
     * 
     * <p>You may customize this method to allocate resources that are required
     * for the lifetime of the current request.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("Authentication Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>This method is called when this bean is removed from
     * request scope.  This occurs automatically when the corresponding
     * HTTP response has been completed and sent to the client.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the request.</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean getApplicationBean() {
        return (ApplicationBean) getBean("ApplicationBean");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean getSessionBean() {
        return (SessionBean) getBean("SessionBean");
    }

    /**
     * Identifie l'utilisateur (manager)
     * S'il est trouvé, il sera stocker en session
     * @param form
     * @throws javax.persistence.NoResultException
     * @throws javax.persistence.NonUniqueResultException
     */
    public void identifyUser(Login form) throws IllegalAuthenticationException, InputDataException {
        Integer idLogged = Integer.valueOf((String) form.getUserLogged().getSelected());
        String login = form.getFldLogin().getValueAsString(getFacesContext());
        String pwd = form.getFldPassword().getPassword().toString();
        if (idLogged != null && idLogged == 1) {
            if (login.split("@").length == 2) {
                try {
                    Manager logged = authentication.connectManager(login, pwd);
                    getSessionBean().setCurrentManager(logged);
                    getSessionBean().setUserLogged(idLogged);
                    getSessionBean().initializeManagerLoggedHotels();
                } catch (IllegalAuthenticationException noR) {
                    throw new IllegalAuthenticationException("Utilisateur non identifié!!");
                }
            } else {
                throw new InputDataException("Login incorrect !!");
            }
        }else if(idLogged != null && idLogged == 0){
            if (login.split("@").length == 2) {
                try {
                    Agency logged = authentication.connectAgency(login, pwd);
                    getSessionBean().setCurrentAgency(logged);
                    getSessionBean().setUserLogged(idLogged);
                } catch (IllegalAuthenticationException noR) {
                    throw new IllegalAuthenticationException("Utilisateur non identifié!!");
                }
            } else {
                throw new InputDataException("Login incorrect !!");
            }
        }else{
            throw new InputDataException("Problème d'authentification !!");
        }
    }
}
